package org.java.shopping.filter;

import org.apache.commons.lang.StringUtils;
import org.java.auth.pojo.UserInfo;
import org.java.auth.utils.JwtUtils;
import org.java.common.util.CookieUtils;
import org.java.shopping.conf.AllowPathsProperties;
import org.java.shopping.conf.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author WHQ
 * @version 1.0
 * @date 2022-3-12 0012 下午 1:59
 * 验证token的过滤器
 *  * 此过滤要拦截用户请求，从请求中得到token
 *  * 解析token，判断用户是否登录
 *  * 如果未登录，就转向到登录界面
 */
@Component
@EnableConfigurationProperties({AllowPathsProperties.class, JwtProperties.class})
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private AllowPathsProperties allowPathsProperties;
    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //得到请求
        ServerHttpRequest request = exchange.getRequest();
        //获得请求的路径
        String path = request.getURI().toString();
        System.out.println(path);
        //得到白名单
        List<String> list = allowPathsProperties.getAllowPaths();
        for (String url : list) {
            if (StringUtils.contains(path,url)){
                System.out.println("可以放行");
                //放行
                return chain.filter(exchange);
            }
        }

        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        if (!cookies.containsKey(jwtProperties.getCookieName())|| CollectionUtils.isEmpty(cookies)){
            //cookie中不存在指定的cookie，或者cookie为空
            //响应未认证
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束请求
            return exchange.getResponse().setComplete();
        }
        //获得请求
        HttpCookie cookie = cookies.getFirst(jwtProperties.getCookieName());
        //得到token
        String token = cookie.getValue();
        System.out.println("token:"+token);
        //通过请求，得到存放在cookie中的token,需要用到cookie工具类
//        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        if (StringUtils.isBlank(token)) {
            //token为空
            System.out.println("非法用户");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
        }else {
            //不为空。token有值，开始解析token，得到载荷对象
            try {
                //解析成功，代表token，正确
                UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
                System.out.println(userInfo.getId());
                System.out.println("解析成功");
            } catch (Exception e) {
                System.out.println("解析失败");
                e.printStackTrace();
                //解析失败，token错误
                //设置错误状态码
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                //请求结束
                return exchange.getResponse().setComplete();
            }
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
